import requests
import time
from utils import USER_AGENT


class BilibiliDanmu:
    """单直播间弹幕发送类"""

    def __init__(self, room_id: str, csrf_token: str, cookies: dict):
        self.room_id = room_id.strip()
        self.csrf_token = csrf_token
        self.cookies = cookies
        self.headers = {
            'User-Agent': USER_AGENT,
            'Content-Type': 'application/x-www-form-urlencoded',
            'Referer': f'https://live.bilibili.com/{self.room_id}',
            'Origin': 'https://live.bilibili.com'
        }
        self.session = requests.Session()
        self.session.cookies.update(cookies)

    def send_danmu(self, message: str) -> tuple[bool, str]:
        """发送单条弹幕"""
        if not message.strip():
            return False, "弹幕内容为空"
        if len(message) > 40:  # B站弹幕最大长度限制
            return False, "弹幕内容超过40字限制"

        data = {
            'msg': message.strip(),
            'roomid': self.room_id,
            'csrf': self.csrf_token,
            'csrf_token': self.csrf_token,
            'rnd': int(time.time()),
            'bubble': 0,
            'mode': 1,  # 滚动弹幕
            'fontsize': 25,
            'color': 16777215  # 白色
        }

        try:
            response = self.session.post("https://api.live.bilibili.com/msg/send", headers=self.headers, data=data)
            result = response.json()

            if response.status_code == 200 and result.get('code') == 0:
                return True, f"发送成功: {message[:20]}..."
            else:
                return False, f"发送失败: {result.get('message', '未知错误')}"
        except Exception as e:
            return False, f"发送异常: {str(e)}"


class DanmuSenderManager:
    """多直播间弹幕发送管理器"""

    def __init__(self, cookies: dict, csrf_token: str):
        self.cookies = cookies
        self.csrf_token = csrf_token
        self.senders = {}  # 缓存：room_id -> BilibiliDanmu实例

    def get_sender(self, room_id: str) -> BilibiliDanmu:
        """获取指定房间的发送实例（不存在则创建）"""
        room_id = room_id.strip()
        if room_id not in self.senders:
            self.senders[room_id] = BilibiliDanmu(room_id, self.csrf_token, self.cookies)
        return self.senders[room_id]

    def update_cookies(self, cookies: dict, csrf_token: str) -> None:
        """更新Cookie（登录状态变化时调用）"""
        self.cookies = cookies
        self.csrf_token = csrf_token
        # 更新已存在的发送实例Cookie
        for sender in self.senders.values():
            sender.cookies = cookies
            sender.csrf_token = csrf_token
            sender.session.cookies.update(cookies)